<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from "vue";
import Editor, {
  BlockType,
  Command,
  ControlType,
  EditorZone,
  ElementType,
  IBlock,
  ICatalogItem,
  IContextMenuContext,
  IElement,
  IRangeStyle,
  KeyMap,
  ListStyle,
  ListType,
  PageMode,
  PaperDirection,
  RowFlex,
  splitText,
  TextDecorationStyle,
  TitleLevel,
} from "@hufe921/canvas-editor";
import { ElMessage, ElPopover } from "element-plus";
import { TableConfig } from "../../../components/table-insert/types";
import { useFileDialog } from "@vueuse/core";
import HyperlinkDialog from "../../../components/dialog/hyperlink-dialog.vue";
import {
  CodeBlockData,
  CommentData,
  ContentBlockData,
  ControlData,
  ControlValueItem,
  HyperlinkData,
  LatexData,
  SearchReplaceData,
  SignatureData,
  WatermarkData,
} from "../../../components/dialog/types";
import CodeBlockDialog from "../../../components/dialog/code-block-dialog.vue";
import WatermarkDialog from "../../../components/dialog/watermark-dialog.vue";
import ColorPanel from "../../../components/color-panel/color-panel.vue";
import ControlDialog from "../../../components/dialog/control-dialog.vue";
import { objectCloneDeep } from "../../../util/ObjectUtils";
import LatexDialog from "../../../components/dialog/latex-dialog.vue";
import {
  getCurrentDateString,
  getCurrentDateTimeString,
} from "../../../util/dateUtils";
import ContentBlockDialog from "../../../components/dialog/content-block-dialog.vue";
import SearchReplaceDialog from "../../../components/dialog/search-replace-dialog.vue";
import SignatureDialog from "../../../components/dialog/signature-dialog.vue";
import CommentDialog from "../../../components/dialog/comment-dialog.vue";
import codeblockPlugin from "@hufe921/canvas-editor-plugin-codeblock";
import docxPlugin from "@hufe921/canvas-editor-plugin-docx";
import { useRoute } from "vue-router";
import { getModelDetailApi } from "../../../api/modelApi";
import { postDownloadFileFromFileServer } from "../../../api/http";
import { replaceFile } from "../../../api/fileUploadApi";
import { replaceFileUrl } from "../../../util/StringUtils";
import { createFileWithContent } from "../../../util/fileUtils";

const wordEditorRef = ref<HTMLDivElement>();
const editor = ref<Editor>();
const { open, reset, onCancel, onChange } = useFileDialog({
  accept: "image/*",
});

const route = useRoute();
const fileId = ref<number>();
const fileInfo = ref<any>({})
if (route.query.fileId) {
  fileId.value = parseInt(route.query.fileId as string);
}

const {
  open: openDocx,
  reset: resetDocx,
  onCancel: onCancelDocx,
  onChange: onChangeDocx,
} = useFileDialog({
  accept:
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  multiple: false,
});

interface WordCommentData {
  id: string;
  content: string;
  userName: string;
  rangeText: string;
  createdDate: string;
}

const commentList: WordCommentData[] = [];

onChange((files) => {
  if (!files || files.length === 0) {
    return;
  }
  for (const file of files) {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = function () {
      // 计算宽高
      const image = new Image();
      const value = fileReader.result as string;
      image.src = value;
      image.onload = function () {
        editor.value?.command.executeImage({
          value,
          width: image.width,
          height: image.height,
        });
        reset();
      };
    };
  }
});

onCancel(() => {
  reset();
});
// 字体相关状态
const currentFont = ref("Microsoft YaHei");
const currentFontSize = ref(16);

// 字体选项
const fontOptions = [
  {
    label: "微软雅黑",
    value: "Microsoft YaHei",
  },

  {
    label: "华文宋体",
    value: "STSong-Light",
  },
  {
    label: "华文黑体",
    value: "STHeiti",
  },
  {
    label: "华文仿宋",
    value: "STFangsong",
  },
  {
    label: "华文楷体",
    value: "STKaiti",
  },
  {
    label: "华文琥珀",
    value: "STHupo",
  },
  {
    label: "华文隶书",
    value: "STLiti",
  },
  {
    label: "华文新魏",
    value: "STXinwei",
  },
  {
    label: "华文行楷",
    value: "STXingkai",
  },
  {
    label: "Arial",
    value: "Arial",
  },
  {
    label: "Segoe UI",
    value: "Segoe UI",
  },
  {
    label: "Ink Free",
    value: "Ink Free",
  },
  {
    label: "Fantasy",
    value: "Fantasy",
  },
];

// 字号选项
const fontSizeOptions = [
  {
    label: "初号",
    value: 48,
  },
  {
    label: "小初",
    value: 42,
  },
  {
    label: "一号",
    value: 36,
  },
  {
    label: "小一",
    value: 30,
  },
  {
    label: "二号",
    value: 24,
  },
  {
    label: "小二",
    value: 22,
  },
  {
    label: "三号",
    value: 18,
  },
  {
    label: "小三",
    value: 16,
  },
  {
    label: "四号",
    value: 14,
  },
  {
    label: "小四",
    value: 12,
  },
  {
    label: "五号",
    value: 10.5,
  },
  {
    label: "小五",
    value: 9,
  },
  {
    label: "六号",
    value: 7.5,
  },
  {
    label: "小六",
    value: 6.5,
  },
  {
    label: "七号",
    value: 6,
  },
  {
    label: "八号",
    value: 5.5,
  },
];

const initWord = (text:any, header:any,footer:any) => {
  if(!wordEditorRef.value) {
    return
  }
  editor.value = new Editor(wordEditorRef.value, {
    header: header,
    footer: footer,
    main: text,
  });
    editor.value.use(codeblockPlugin);
    editor.value.use(docxPlugin);
    // 设置
    editor.value.command.executeSetLocale("zh-CN");
    editor.value.eventBus.on("input", handleInput);
    editor.value.eventBus.on("rangeStyleChange", handleRangeStyleChange);
    editor.value.eventBus.on("pageScaleChange", handlePageScaleChange);
    editor.value.eventBus.on("contentChange", handleContentChange);
    editor.value.eventBus.on(
      "intersectionPageNoChange",
      handleIntersectionPageNoChange
    );
    editor.value.eventBus.on("pageModeChange", handlePageModeChange);
    editor.value.eventBus.on("pageSizeChange", handlePageSizeChange);

    // 9. 右键菜单注册
    editor.value.register.contextMenuList([
      {
        name: "批注",
        when: (payload: IContextMenuContext) => {
          return (
            !payload.isReadonly &&
            payload.editorHasSelection &&
            payload.zone === EditorZone.MAIN
          );
        },
        callback: (command: Command, context: IContextMenuContext) => {
          handleComment();
        },
      },
      {
        name: "签名",
        icon: "signature",
        when: (payload) => {
          return !payload.isReadonly && payload.editorTextFocus;
        },
        callback: (command: Command, context: IContextMenuContext) => {
          handleSignature();
        },
      },
      {
        name: "格式整理",
        icon: "word-tool",
        when: (payload: IContextMenuContext) => {
          return !payload.isReadonly;
        },
        callback: (command: Command, context: IContextMenuContext) => {
          command.executeWordTool();
        },
      },
      {
        name: "保存",
        icon: "save",
        when: (payload: IContextMenuContext) => {
          return !payload.isReadonly;
        },
        callback: (command: Command, context: IContextMenuContext) => {
          handleSave()
        },
      }
    ]);

    //10 注册快捷键
    editor.value?.register.shortcutList([{
      key: KeyMap.S,
      ctrl: true,
      mod: true,
      callback: () => {
        handleSave()
      },
    }]);
}

const handleSave = () => {
  const value = editor.value?.command.getValue();
  if(value) {
    const file = createFileWithContent("word.json",JSON.stringify(value.data), "application/json")
    replaceFile(replaceFileUrl(fileInfo.value.url), file).then((res) => {
      ElMessage.success("保存成功")
    })
  }
}

onMounted(async () => {
  if (wordEditorRef.value) {
    const data = await getModelDetailApi(fileId.value as number, "id,name,url","document.file")
     fileInfo.value = data
    const response = await postDownloadFileFromFileServer(fileInfo.value.url, {})
    response.data.text().then((text: string) => {
      if(text.startsWith("{")) {
        const json = JSON.parse(text)
        initWord(json.main, json.header, json.footer)
      } else {
        initWord([], [], [])
        const instance =  editor.value as any;
        instance.command.executeImportDocx({arrayBuffer:response.data});
      }
       // 初始化文档统计信息
      setTimeout(() => {
        updateDocumentStats();
      }, 100);
    })
  }
});

onUnmounted(() => {
  editor.value?.eventBus.off("input", handleInput);
  editor.value?.eventBus.off("rangeStyleChange", handleRangeStyleChange);
  editor.value?.eventBus.off("pageScaleChange", handlePageScaleChange);
  editor.value?.eventBus.off("contentChange", handleContentChange);
  editor.value?.eventBus.off(
    "intersectionPageNoChange",
    handleIntersectionPageNoChange
  );
  editor.value?.eventBus.off("pageModeChange", handlePageModeChange);
  editor.value?.eventBus.off("pageSizeChange", handlePageSizeChange);
  // 清理目录拖拽事件监听器
  document.removeEventListener("mousemove", handleCatalogMouseMove);
  document.removeEventListener("mouseup", handleCatalogMouseUp);

  // 清理批注面板拖拽事件监听器
  document.removeEventListener("mousemove", handleCommentMouseMove);
  document.removeEventListener("mouseup", handleCommentMouseUp);
});

const handleInput = (evt: Event) => {};

//选区样式发生改变
const handleRangeStyleChange = (payload: IRangeStyle) => {
  canUndo.value = payload.undo;
  canRedo.value = payload.redo;
  painterActive.value = payload.painter;

  // 更新字体状态
  if (payload.font) {
    currentFont.value = payload.font;
  }
  if (payload.size) {
    currentFontSize.value = payload.size;
  }
  if (payload.color) {
    currentFontColor.value = payload.color;
  } else {
    currentFontColor.value = "#000000";
  }

  if (payload.highlight) {
    currentHighlightColor.value = payload.highlight;
  } else {
    currentHighlightColor.value = "#ffffFF";
  }

  boldActive.value = payload.bold;
  italicActive.value = payload.italic;
  underlineActive.value = payload.underline;
  strikeoutActive.value = payload.strikeout;
  if (payload.type == ElementType.SUPERSCRIPT) {
    superscriptActive.value = true;
  } else {
    superscriptActive.value = false;
  }
  if (payload.type == ElementType.SUBSCRIPT) {
    subscriptActive.value = true;
  } else {
    subscriptActive.value = false;
  }

  if (payload.level) {
    currentTitleLevel.value = payload.level;
  } else {
    currentTitleLevel.value = "";
  }

  if (payload.rowFlex && payload.rowFlex === "right") {
    currentAlignment.value = RowFlex.RIGHT;
  } else if (payload.rowFlex && payload.rowFlex === "center") {
    currentAlignment.value = RowFlex.CENTER;
  } else if (payload.rowFlex && payload.rowFlex === "alignment") {
    currentAlignment.value = RowFlex.ALIGNMENT;
  } else if (payload.rowFlex && payload.rowFlex === "justify") {
    currentAlignment.value = RowFlex.JUSTIFY;
  } else {
    currentAlignment.value = RowFlex.LEFT;
  }

  if (payload.type === ElementType.SEPARATOR) {
    separatorActive.value = true;
  } else {
    separatorActive.value = false;
  }

  // 更新文档统计信息
  updateDocumentStats();
};

//页面缩放发生改变
const handlePageScaleChange = (payload: number) => {
  pageScale.value = Math.floor(payload * 10 * 10);
};

//内容发生改变
const handleContentChange = () => {
  updateCatalog();
  updateDocumentStats();
};

const handleIntersectionPageNoChange = (payload: number) => {
  // 获取页面信息
  console.log("handleIntersectionPageNoChange", payload);
  documentStats.value.currentPage = payload + 1 || 1;
};

const handlePageModeChange = (payload: PageMode) => {};

const handlePageSizeChange = (payload: number) => {
  documentStats.value.totalPages = payload || 1;
};

const canUndo = ref(false);
const canRedo = ref(false);

// 撤销事件处理
const handleUndo = () => {
  if (canUndo.value) {
    editor.value?.command.executeUndo();
  }
};

// 重做事件处理
const handleRedo = () => {
  if (canRedo.value) {
    editor.value?.command.executeRedo();
  }
};

// 字体相关方法
const handleFontChange = (font: string) => {
  editor.value?.command.executeFont(font);
};

const handleFontSizeChange = (size: number) => {
  editor.value?.command.executeSize(size);
};

let isFirstClick = true;
let painterTimeout: number;
const painterActive = ref(false);
const handlePainter = () => {
  if (isFirstClick) {
    isFirstClick = false;
    painterTimeout = window.setTimeout(() => {
      console.log("painter-click");
      isFirstClick = true;
      editor.value?.command.executePainter({
        isDblclick: false,
      });
    }, 200);
  } else {
    window.clearTimeout(painterTimeout);
  }
};

const handleDoubleClickPainter = () => {
  isFirstClick = true;
  window.clearTimeout(painterTimeout);
  editor.value?.command.executePainter({
    isDblclick: true,
  });
};

const handleFormat = () => {
  editor.value?.command.executeFormat();
};

const handleSizeAdd = () => {
  editor.value?.command.executeSizeAdd();
};

const handleSizeReduce = () => {
  editor.value?.command.executeSizeMinus();
};

const boldActive = ref(false);
const handleBold = () => {
  editor.value?.command.executeBold();
};

const italicActive = ref(false);
const handleItalic = () => {
  editor.value?.command.executeItalic();
};

const underlineActive = ref(false);
const handleUnderline = () => {
  editor.value?.command.executeUnderline();
};

const handleUnderlineType = (type: TextDecorationStyle) => {
  editor.value?.command.executeUnderline({
    style: type,
  });
};

const strikeoutActive = ref(false);
const handleStrikeout = () => {
  editor.value?.command.executeStrikeout();
};

const superscriptActive = ref(false);
const handleSuperscript = () => {
  editor.value?.command.executeSuperscript();
};

const subscriptActive = ref(false);
const handleSubscript = () => {
  editor.value?.command.executeSubscript();
};

const currentFontColor = ref("#000000");
const colorPanelRef = ref<InstanceType<typeof ElPopover>>();
const handleFontColorChange = (color: string) => {
  editor.value?.command.executeColor(color);
  colorPanelRef.value?.hide();
};

const currentHighlightColor = ref("#FFFFFF");
const highlightColorPanelRef = ref<InstanceType<typeof ElPopover>>();
const handleHighlightColorChange = (color: string) => {
  editor.value?.command.executeHighlight(color);
  highlightColorPanelRef.value?.hide();
};

const currentTitleLevel = ref("");
const titleLevelLabel = computed(() => {
  return titleLevelOptions.find(
    (item) => item.value === currentTitleLevel.value
  )?.label;
});

const titleLevelOptions = [
  {
    label: "正文",
    value: "",
    size: 16,
  },
  {
    label: "标题1",
    value: "first",
    size: 26,
  },
  {
    label: "标题2",
    value: "second",
    size: 24,
  },
  {
    label: "标题3",
    value: "third",
    size: 22,
  },

  {
    label: "标题4",
    value: "fourth",
    size: 20,
  },
  {
    label: "标题5",
    value: "fifth",
    size: 18,
  },
  {
    label: "标题6",
    value: "sixth",
    size: 16,
  },
];

const handleTitleLevelChange = (value: TitleLevel) => {
  editor.value?.command.executeTitle(value || null);
  currentTitleLevel.value = value;
};

const currentAlignment = ref<RowFlex>(RowFlex.LEFT);
const handleAlignmentChange = (value: RowFlex) => {
  editor.value?.command.executeRowFlex(value);
  currentAlignment.value = value;
};

//行间距选项
const rowMarginOptions = [
  {
    label: "1",
    value: 1,
  },
  {
    label: "1.5",
    value: 1.5,
  },
  {
    label: "1.75",
    value: 1.75,
  },
  {
    label: "2",
    value: 2,
  },
  {
    label: "2.5",
    value: 2.5,
  },
  {
    label: "3",
    value: 3,
  },
];

const handleRowMarginChange = (value: number) => {
  editor.value?.command.executeRowMargin(value);
};

const handleListChange = (value: ListStyle) => {
  if (value) {
    editor.value?.command.executeList(
      value == ListStyle.DECIMAL ? ListType.OL : ListType.UL,
      value
    );
  } else {
    editor.value?.command.executeList(null);
  }
};

const tableInsertPanelRef = ref<InstanceType<typeof ElPopover>>();
const handleInsertTable = (tableConfig: TableConfig) => {
  editor.value?.command.executeInsertTable(tableConfig.rows, tableConfig.cols);
  tableInsertPanelRef.value?.hide();
};

const handleInsertImage = () => {
  open();
};

const hyperlinkDialogVisible = ref(false);
const handleHyperlink = () => {
  hyperlinkDialogVisible.value = true;
};

const handleHyperlinkConfirm = (data: HyperlinkData) => {
  editor.value?.command.executeHyperlink({
    type: ElementType.HYPERLINK,
    value: "",
    url: data.link,
    valueList: splitText(data.text).map((n: string) => ({
      value: n,
      size: 16,
    })),
  });
  hyperlinkDialogVisible.value = false;
};

const separatorActive = ref(false);
const handleSeparator = (value: string) => {
  let payload: number[] = [];
  const separatorDash = value.split(",").map(Number);
  if (separatorDash) {
    const isSingleLine = separatorDash.every((d) => d === 0);
    if (!isSingleLine) {
      payload = separatorDash;
    }
  }
  editor.value?.command.executeSeparator(payload);
};

const codeBlockDialogVisible = ref(false);
const handleCodeBlock = () => {
  codeBlockDialogVisible.value = true;
};

const handleCodeBlockConfirm = (data: CodeBlockData) => {
  const codeblock = data.code;
  if (!codeblock) return;
  const instance: any = editor.value;
  instance.command.executeInsertCodeblock(codeblock);

  codeBlockDialogVisible.value = false;
};

// 水印对话框状态
const watermarkDialogVisible = ref(false);

const handleWatermark = (command: string) => {
  if (command === "watermark") {
    watermarkDialogVisible.value = true;
  } else if (command === "remove-watermark") {
    editor.value?.command.executeDeleteWatermark();
  }
};

const handleWatermarkConfirm = (data: WatermarkData) => {
  editor.value?.command.executeAddWatermark({
    data: data.content,
    color: data.color,
    size: Number(data.fontSize),
    opacity: Number(data.opacity),
    repeat: data.repeat === 1,
    gap:
      data.repeat === 1 && data.horizontalSpacing && data.verticalSpacing
        ? [Number(data.horizontalSpacing), Number(data.verticalSpacing)]
        : undefined,
  });

  watermarkDialogVisible.value = false;
};

const handleWatermarkCancel = () => {
  watermarkDialogVisible.value = false;
};

const handlePageBreak = () => {
  editor.value?.command.executePageBreak();
};

const handleCheckbox = () => {
  editor.value?.command.executeInsertElementList([
    {
      type: ElementType.CHECKBOX,
      value: "",
      checkbox: {
        value: false,
      },
    },
  ]);
};

const handleRadio = () => {
  editor.value?.command.executeInsertElementList([
    {
      type: ElementType.RADIO,
      value: "",
      radio: {
        value: false,
      },
    },
  ]);
};

const controlDialogVisible = ref(false);
const controlDialogTitle = ref("文本控件");
const controlDialogData = ref<ControlData>({
  type: "text",
  placeholder: "",
  defaultValue: "",
});
const handleControl = (command: string) => {
  switch (command) {
    case "text":
      controlDialogTitle.value = "文本控件";
      controlDialogData.value = {
        type: "text",
        placeholder: "",
        defaultValue: "",
      };
      break;
    case "number":
      controlDialogTitle.value = "数值控件";
      controlDialogData.value = {
        type: "number",
        placeholder: "",
        defaultValue: "",
      };
      break;
    case "enum":
      controlDialogTitle.value = "枚举控件";
      controlDialogData.value = {
        type: "enum",
        placeholder: "",
        defaultValue: "",
        valueSet: [],
      };
      break;
    case "date":
      controlDialogTitle.value = "日期控件";
      controlDialogData.value = {
        type: "date",
        placeholder: "",
        defaultValue: "",
        dateFormat: "yyyy-MM-dd",
      };
      break;
    case "checkbox":
      controlDialogTitle.value = "复选框控件";
      controlDialogData.value = {
        type: "checkbox",
        placeholder: "",
        defaultValue: "",
        valueSet: [],
      };
      break;
    default:
      controlDialogTitle.value = "单选框控件";
      controlDialogData.value = {
        type: "radio",
        placeholder: "",
        defaultValue: "",
        valueSet: [],
      };
      break;
  }
  controlDialogVisible.value = true;
};
const handleControlConfirm = (data: ControlData) => {
  let value: IElement | undefined;
  let valueSets: ControlValueItem[] | undefined;
  switch (data.type) {
    case "text":
      value = {
        type: ElementType.CONTROL,
        value: "",
        control: {
          type: ControlType.TEXT,
          placeholder: data.placeholder,
          value: data.defaultValue ? [{ value: data.defaultValue }] : null,
        },
      };
      break;
    case "number":
      value = {
        type: ElementType.CONTROL,
        value: "",
        control: {
          type: ControlType.NUMBER,
          placeholder: data.placeholder,
          value: data.defaultValue ? [{ value: data.defaultValue }] : null,
        },
      };
      break;
    case "date":
      value = {
        type: ElementType.CONTROL,
        value: "",
        control: {
          type: ControlType.DATE,
          dateFormat: data.dateFormat,
          value: data.defaultValue ? [{ value: data.defaultValue }] : null,
          placeholder: data.placeholder,
        },
      };
      break;
    case "checkbox":
      valueSets = objectCloneDeep(data.valueSet);
      if (!valueSets) return;
      value = {
        type: ElementType.CONTROL,
        value: "",
        control: {
          type: ControlType.CHECKBOX,
          code: "",
          value: data.defaultValue ? [{ value: data.defaultValue }] : null,
          placeholder: data.placeholder,
          valueSets: valueSets,
        },
      };
      break;
    case "radio":
      valueSets = objectCloneDeep(data.valueSet);
      if (!valueSets) return;
      value = {
        type: ElementType.CONTROL,
        value: "",
        control: {
          type: ControlType.RADIO,
          code: "",
          value: data.defaultValue ? [{ value: data.defaultValue }] : null,
          placeholder: data.placeholder,
          valueSets: valueSets,
        },
      };
      break;
    case "enum":
      valueSets = objectCloneDeep(data.valueSet);
      if (!valueSets) return;
      value = {
        type: ElementType.CONTROL,
        value: "",
        control: {
          type: ControlType.SELECT,
          code: "",
          value: data.defaultValue ? [{ value: data.defaultValue }] : null,
          placeholder: data.placeholder,
          valueSets: valueSets,
        },
      };
      break;
  }
  if (value) {
    editor.value?.command.executeInsertControl(value);
  }
};
const handleControlCancel = () => {
  controlDialogVisible.value = false;
};
const latexDialogVisible = ref(false);
const handleLatex = () => {
  latexDialogVisible.value = true;
};
const handleLatexConfirm = (data: LatexData) => {
  editor.value?.command.executeInsertElementList([
    {
      type: ElementType.LATEX,
      value: data.content,
    },
  ]);
  latexDialogVisible.value = false;
};

const handleDate = (command: string) => {
  if (command === "date") {
    editor.value?.command.executeInsertElementList([
      {
        type: ElementType.DATE,
        value: "",
        dateFormat: "yyyy-MM-dd",
        valueList: [{ value: getCurrentDateString() }],
      },
    ]);
  } else if (command === "datetime") {
    editor.value?.command.executeInsertElementList([
      {
        type: ElementType.DATE,
        value: "",
        dateFormat: "yyyy-MM-dd hh:mm",
        valueList: [{ value: getCurrentDateTimeString() }],
      },
    ]);
  }
};

const contentBlockDialogVisible = ref(false);
const handleContentBlock = () => {
  contentBlockDialogVisible.value = true;
};
const handleContentBlockConfirm = (data: ContentBlockData) => {
  const block: IBlock = {
    type: <BlockType>data.type,
  };
  if (block.type === BlockType.IFRAME) {
    if (!data.address && !data.html) return;
    block.iframeBlock = {
      src: data.address,
      srcdoc: data.html,
    };
  } else if (block.type === BlockType.VIDEO) {
    if (!data.address) return;
    block.videoBlock = {
      src: data.address,
    };
  }
  const blockElement: IElement = {
    type: ElementType.BLOCK,
    value: "",
    height: Number(data.height),
    block,
  };
  if (data.width) {
    blockElement.width = Number(data.width);
  }
  editor.value?.command.executeInsertElementList([blockElement]);

  contentBlockDialogVisible.value = false;
};

const searchReplaceDialogVisible = ref(false);
const handleSearchReplace = () => {
  searchReplaceDialogVisible.value = true;
};

// 签名对话框状态
const signatureDialogVisible = ref(false);
const handleSignature = () => {
  signatureDialogVisible.value = true;
};

const handleSignatureConfirm = (data: SignatureData) => {
  editor.value?.command.executeInsertElementList([
    {
      type: ElementType.IMAGE,
      value: data.value,
      width: data.width,
      height: data.height,
    },
  ]);
  signatureDialogVisible.value = false;
};

// 搜索替换相关函数
const handleEnter = (data: SearchReplaceData) => {
  editor.value?.command.executeSearch(data.findText);
  setSearchResult();
};
const handleChange = (data: SearchReplaceData) => {
  editor.value?.command.executeSearch(data.findText);
  setSearchResult();
};
const handleFindNext = (data: SearchReplaceData) => {
  editor.value?.command.executeSearchNavigateNext();
  setSearchResult();
};

const handleFindPrevious = (data: SearchReplaceData) => {
  // canvas-editor 的向上搜索功能
  editor.value?.command.executeSearchNavigatePre();
  setSearchResult();
};

const handleReplace = (data: SearchReplaceData) => {
  // 执行替换操作
  if (searchIndex.value >= 0 && searchCount.value > 0) {
    editor.value?.command.executeReplace(data.replaceText, {
      index: searchIndex.value - 1,
    });
  }
};

const handleReplaceAll = (data: SearchReplaceData) => {
  if (searchIndex.value >= 0 && searchCount.value > 0) {
    editor.value?.command.executeReplace(data.replaceText);
  }
};
const searchIndex = ref(0);
const searchCount = ref(0);
function setSearchResult() {
  const result = editor.value?.command.getSearchNavigateInfo();
  if (result) {
    const { index, count } = result;
    searchIndex.value = index;
    searchCount.value = count;
  } else {
    searchIndex.value = -1;
    searchCount.value = 0;
  }
}

const handleSearchReplaceClose = () => {
  searchReplaceDialogVisible.value = false;
};

const handlePrint = () => {
  editor.value?.command.executePrint();
};

const handleWord = (command: string) => {
  if (command === "import") {
    openDocx();
  } else if (command === "export") {
    const instance: any = editor.value;
    instance.command.executeExportDocx({
      fileName: "test",
    });
  }
};

onChangeDocx((files) => {
  if (!files || files.length === 0) {
    return;
  }
  const file = files[0];
  const reader = new FileReader();
  reader.onload = (e) => {
    const content = e.target?.result as ArrayBuffer;
    const instance: any = editor.value;
    instance.command.executeImportDocx({arrayBuffer:content});
  };
  reader.readAsArrayBuffer(file);
});

onCancelDocx(() => {
  resetDocx();
});

// 底部
const handleCatalog = () => {
  console.log("目录");
  catalogVisible.value = !catalogVisible.value;
  if (catalogVisible.value) {
    updateCatalog();
  }
};

// 批注面板切换
const handleCommentPanel = () => {
  commentVisible.value = !commentVisible.value;
};

// 页面模式状态
const pageMode = ref("paging"); // 'paging' 分页模式, 'continuity' 连页模式

// 文档统计信息
const documentStats = ref({
  currentPage: 1,
  totalPages: 1,
  wordCount: 0,
  lineCount: 0,
  columnCount: 0,
});

// 处理页面模式切换
const handlePageMode = (mode: string) => {
  pageMode.value = mode;
  if (mode === "paging") {
    // 设置为分页模式
    editor.value?.command.executePageMode(PageMode.PAGING);
  } else if (mode === "continuity") {
    // 设置为连页模式
    editor.value?.command.executePageMode(PageMode.CONTINUITY);
  }
};

const pageSize = ref("794*1123");
const handlePageSize = (size: string) => {
  pageSize.value = size;
  const [width, height] = size.split("*").map(Number);
  editor.value?.command.executePaperSize(width, height);
};

// 更新文档统计信息
const updateDocumentStats = async () => {
  if (!editor.value) return;

  try {
    // 获取字数统计
    const wordCount = await editor.value.command.getWordCount();
    if (typeof wordCount === "number") {
      documentStats.value.wordCount = wordCount;
    }

    // 获取当前位置信息
    const positionInfo = editor.value.command.getRangeContext?.();
    if (positionInfo) {
      documentStats.value.lineCount = positionInfo.startRowNo + 1 || 1;
      documentStats.value.columnCount = positionInfo.startColNo + 1 || 1;
    }
  } catch (error) {
    // 如果 API 不存在或出错，使用默认值
    console.warn("获取文档统计信息失败:", error);
  }
};

const catalogDatas = ref<ICatalogItem[]>([]);

// el-tree 配置
const treeProps = {
  children: "subCatalog",
  label: "name",
};

// 转换目录数据为树形结构
const treeData = computed(() => {
  return buildTreeData(catalogDatas.value);
});

// 构建树形数据结构
const buildTreeData = (items: ICatalogItem[]): ICatalogItem[] => {
  const result: ICatalogItem[] = [];
  const stack: { item: ICatalogItem; level: number }[] = [];

  for (const item of items) {
    const levelMap: { [key: string]: number } = {
      first: 1,
      second: 2,
      third: 3,
      fourth: 4,
      fifth: 5,
      sixth: 6,
    };

    const currentLevel = levelMap[item.level as string] || 1;

    // 创建新的项目副本
    const newItem: ICatalogItem = {
      ...item,
      subCatalog: [],
    };

    // 找到正确的父级
    while (stack.length > 0 && stack[stack.length - 1].level >= currentLevel) {
      stack.pop();
    }

    if (stack.length === 0) {
      // 顶级项目
      result.push(newItem);
    } else {
      // 添加到父级的子项
      const parent = stack[stack.length - 1].item;
      if (!parent.subCatalog) {
        parent.subCatalog = [];
      }
      parent.subCatalog.push(newItem);
    }

    stack.push({ item: newItem, level: currentLevel });
  }

  return result;
};

async function updateCatalog() {
  const catalog = await editor.value?.command.getCatalog();

  if (catalog) {
    catalogDatas.value = catalog;
  }
}

const catalogVisible = ref(false);

// 目录面板拖拽相关状态
const catalogPosition = ref({ x: 20, y: 60 }); // 初始位置：左上角，顶部留出工具栏高度
const isDragging = ref(false);
const dragStartPos = ref({ x: 0, y: 0 });
const catalogPanelRef = ref<HTMLDivElement>();

// 目录拖拽事件处理
const handleCatalogMouseDown = (e: MouseEvent) => {
  // 只有点击标题栏才能拖拽
  const target = e.target as HTMLElement;
  if (!target.closest(".catalog-header")) return;

  isDragging.value = true;
  dragStartPos.value = {
    x: e.clientX - catalogPosition.value.x,
    y: e.clientY - catalogPosition.value.y,
  };

  // 添加全局事件监听
  document.addEventListener("mousemove", handleCatalogMouseMove);
  document.addEventListener("mouseup", handleCatalogMouseUp);

  // 防止文本选择
  e.preventDefault();
};

const handleCatalogMouseMove = (e: MouseEvent) => {
  if (!isDragging.value) return;

  const newX = e.clientX - dragStartPos.value.x;
  const newY = e.clientY - dragStartPos.value.y;

  // 限制拖拽范围，确保面板不会超出视窗
  const maxX = window.innerWidth - 280; // 280px 是面板宽度
  const maxY = window.innerHeight - 200; // 预留底部空间

  catalogPosition.value = {
    x: Math.max(0, Math.min(newX, maxX)),
    y: Math.max(60, Math.min(newY, maxY)), // 60px 是工具栏高度
  };
};

const handleCatalogMouseUp = () => {
  isDragging.value = false;

  // 移除全局事件监听
  document.removeEventListener("mousemove", handleCatalogMouseMove);
  document.removeEventListener("mouseup", handleCatalogMouseUp);
};

const handleCatalogClick = (item: ICatalogItem) => {
  // 目录项点击处理，这里可以根据 canvas-editor 的实际 API 进行实现
  console.log("点击目录项:", item);
  // TODO: 实现跳转到对应标题的功能
  editor.value?.command.executeLocationCatalog(item.id);
};

const getCatalogFontSize = (level: TitleLevel) => {
  switch (level) {
    case "first":
      return "16px";
    case "second":
      return "15px";
    case "third":
      return "14px";
    case "fourth":
      return "13px";
    case "fifth":
      return "12px";
    case "sixth":
      return "12px";
    default:
      return "14px";
  }
};

const getCatalogFontWeight = (level: TitleLevel) => {
  switch (level) {
    case "first":
      return "600";
    case "second":
      return "600";
    case "third":
      return "500";
    case "fourth":
      return "500";
    case "fifth":
      return "400";
    case "sixth":
      return "400";
    default:
      return "400";
  }
};

const paperDirection = ref("vertical");
const handlePaperDirection = (direction: string) => {
  paperDirection.value = direction;
  editor.value?.command.executePaperDirection(direction as PaperDirection);
};

// 页面缩放状态
const pageScale = ref(100); // 缩放百分比

// 页面缩放处理函数
const handlePageScaleAdd = () => {
  editor.value?.command.executePageScaleAdd();
};

const handlePageScaleReduce = () => {
  editor.value?.command.executePageScaleMinus();
};

const handlePageScaleReset = () => {
  editor.value?.command.executePageScaleRecovery();
};

// 批注对话框状态
const commentDialogVisible = ref(false);

// 批注功能
const handleComment = () => {
  // 获取当前选中的文本
  const selectedText = editor.value?.command.getRangeText() || "";

  if (!selectedText.trim()) {
    ElMessage.warning("请先选择要批注的文本");
    return;
  }

  // 显示批注输入对话框
  commentDialogVisible.value = true;
};

// 处理批注确认
const handleCommentConfirm = (content: string) => {
  // 获取当前选中的文本
  const selectedText = editor.value?.command.getRangeText() || "";

  // 设置分组（用于批注关联）
  const groupId = editor.value?.command.executeSetGroup();

  if (groupId) {
    commentList.push({
      id: groupId,
      content: content,
      userName: "用户",
      rangeText: selectedText,
      createdDate: new Date().toLocaleString(),
    });

    ElMessage.success("批注添加成功");

    // 自动显示批注面板
    if (!commentVisible.value) {
      commentVisible.value = true;
    }
  }

  commentDialogVisible.value = false;
};

// 批注面板状态
const commentVisible = ref(false);
const commentPosition = ref({ x: window.innerWidth - 340, y: 60 }); // 初始位置：右侧
const isDraggingComment = ref(false);
const dragStartPosComment = ref({ x: 0, y: 0 });
const commentPanelRef = ref<HTMLDivElement>();

// 批注面板拖拽事件处理
const handleCommentMouseDown = (e: MouseEvent) => {
  // 只有点击标题栏才能拖拽
  const target = e.target as HTMLElement;
  if (!target.closest(".comment-header")) return;

  isDraggingComment.value = true;
  dragStartPosComment.value = {
    x: e.clientX - commentPosition.value.x,
    y: e.clientY - commentPosition.value.y,
  };

  // 添加全局事件监听
  document.addEventListener("mousemove", handleCommentMouseMove);
  document.addEventListener("mouseup", handleCommentMouseUp);

  // 防止文本选择
  e.preventDefault();
};

const handleCommentMouseMove = (e: MouseEvent) => {
  if (!isDraggingComment.value) return;

  const newX = e.clientX - dragStartPosComment.value.x;
  const newY = e.clientY - dragStartPosComment.value.y;

  // 限制拖拽范围，确保面板不会超出视窗
  const maxX = window.innerWidth - 320; // 320px 是面板宽度
  const maxY = window.innerHeight - 200; // 预留底部空间

  commentPosition.value = {
    x: Math.max(0, Math.min(newX, maxX)),
    y: Math.max(60, Math.min(newY, maxY)), // 60px 是工具栏高度
  };
};

const handleCommentMouseUp = () => {
  isDraggingComment.value = false;

  // 移除全局事件监听
  document.removeEventListener("mousemove", handleCommentMouseMove);
  document.removeEventListener("mouseup", handleCommentMouseUp);
};

// 批注项点击事件
const handleCommentClick = (comment: WordCommentData) => {
  // 定位到批注相关的文本
  if (comment.id && editor.value) {
    try {
      editor.value.command.executeLocationGroup(comment.id);
    } catch (error) {
      console.warn("定位批注失败:", error);
    }
  }
};

// 删除批注
const handleDeleteComment = (commentId: string) => {
  const index = commentList.findIndex((comment) => comment.id === commentId);
  if (index !== -1) {
    commentList.splice(index, 1);
    ElMessage.success("批注已删除");

    // 同时删除编辑器中的分组
    if (editor.value) {
      try {
        editor.value.command.executeDeleteGroup(commentId);
      } catch (error) {
        console.warn("删除分组失败:", error);
      }
    }
  }
};
</script>
<template>
  <div class="word-container">
    <div class="word-header flex items-center justify-center">
      <div class="toolbar flex items-center">
        <el-tooltip content="撤销" placement="bottom">
          <div
            :class="[
              'toolbar-item w-[24px] h-[24px] flex items-center justify-center',
              canUndo ? 'cursor-pointer' : 'cursor-not-allowed disabled',
            ]"
            @click="handleUndo"
          >
            <el-image src="/word/tool/undo.svg" />
          </div>
        </el-tooltip>

        <el-tooltip content="重做" placement="bottom">
          <div
            :class="[
              'toolbar-item w-[24px] h-[24px] flex items-center justify-center',
              canRedo ? 'cursor-pointer' : 'cursor-not-allowed disabled',
            ]"
            @click="handleRedo"
          >
            <el-image src="/word/tool/redo.svg" />
          </div>
        </el-tooltip>

        <el-tooltip content="格式刷(双击可以连续使用)" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center',
              painterActive ? 'active' : '',
            ]"
            @click="handlePainter"
            @dblclick="handleDoubleClickPainter"
          >
            <el-image src="/word/tool/painter.svg" />
          </div>
        </el-tooltip>
        <el-tooltip content="格式化" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            @click="handleFormat"
          >
            <el-image src="/word/tool/format.svg" />
          </div>
        </el-tooltip>
        <el-divider direction="vertical" />

        <!-- 字体选择器 -->
        <div class="font-selector flex items-center ml-4">
          <el-select
            v-model="currentFont"
            @change="handleFontChange"
            size="small"
            style="width: 140px"
            placeholder="选择字体"
          >
            <el-option
              v-for="font in fontOptions"
              :key="font.value"
              :label="font.label"
              :value="font.value"
              :style="{ fontFamily: font.value }"
            />
          </el-select>

          <el-select
            v-model="currentFontSize"
            @change="handleFontSizeChange"
            size="small"
            style="width: 80px"
            class="ml-2"
            placeholder="字号"
          >
            <el-option
              v-for="size in fontSizeOptions"
              :key="size.value"
              :label="size.label"
              :value="size.value"
            />
          </el-select>
        </div>

        <el-tooltip content="增大字号" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            @click="handleSizeAdd"
          >
            <el-image src="/word/tool/size-add.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="减小字号" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            @click="handleSizeReduce"
          >
            <el-image
              src="/word/tool/size-minus.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>
        <el-tooltip content="加粗" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center',
              boldActive ? 'active' : '',
            ]"
            @click="handleBold"
          >
            <el-image src="/word/tool/bold.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="斜体" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center',
              italicActive ? 'active' : '',
            ]"
            @click="handleItalic"
          >
            <el-image src="/word/tool/italic.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="下划线" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[48px] h-[24px] flex items-center justify-center ',
              underlineActive ? 'active' : '',
            ]"
            @click="handleUnderline"
          >
            <el-image
              src="/word/tool/underline.svg"
              class="w-[16px] h-[16px]"
            />
            <el-dropdown @command="handleUnderlineType">
              <el-icon class="outline-none"><ArrowDown /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="solid">
                    <el-image
                      src="/word/tool/line-single.svg"
                      class="h-[16px]"
                    />
                  </el-dropdown-item>
                  <el-dropdown-item command="double">
                    <el-image
                      src="/word/tool/line-double.svg"
                      class="h-[16px]"
                    />
                  </el-dropdown-item>
                  <el-dropdown-item command="dashed">
                    <el-image
                      src="/word/tool/line-dash-dot.svg"
                      class="h-[16px]"
                    />
                  </el-dropdown-item>
                  <el-dropdown-item command="dotted">
                    <el-image src="/word/tool/line-dot.svg" class="h-[16px]" />
                  </el-dropdown-item>
                  <el-dropdown-item command="wavy">
                    <el-image src="/word/tool/line-wavy.svg" class="h-[16px]" />
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-tooltip>

        <el-tooltip content="删除线" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center',
              strikeoutActive ? 'active' : '',
            ]"
            @click="handleStrikeout"
          >
            <el-image
              src="/word/tool/strikeout.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>

        <el-tooltip content="上标" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center',
              superscriptActive ? 'active' : '',
            ]"
            @click="handleSuperscript"
          >
            <el-image
              src="/word/tool/superscript.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>

        <el-tooltip content="下标" placement="bottom">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center',
              subscriptActive ? 'active' : '',
            ]"
            @click="handleSubscript"
          >
            <el-image
              src="/word/tool/subscript.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>

        <el-tooltip content="字体颜色" placement="bottom" trigger="click">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex flex-col items-center justify-center"
          >
            <el-image src="/word/tool/color.svg" class="w-[16px] h-[16px]" />
            <el-popover
              ref="colorPanelRef"
              popover-class="p-0"
              width="fit-content"
            >
              <template #reference>
                <div
                  class="w-[18px] h-[4px]"
                  :style="{ backgroundColor: currentFontColor }"
                ></div>
              </template>
              <ColorPanel
                v-model="currentFontColor"
                @change="handleFontColorChange"
              />
            </el-popover>
          </div>
        </el-tooltip>

        <el-tooltip content="高亮" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex flex-col items-center justify-center"
          >
            <el-image
              src="/word/tool/highlight.svg"
              class="w-[16px] h-[16px]"
            />
            <el-popover
              ref="highlightColorPanelRef"
              popover-class="p-0"
              width="fit-content"
            >
              <template #reference>
                <span
                  class="w-[18px] h-[4px]"
                  :style="{ backgroundColor: currentHighlightColor }"
                ></span>
              </template>
              <ColorPanel
                v-model="currentHighlightColor"
                @change="handleHighlightColorChange"
              />
            </el-popover>
          </div>
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-dropdown @command="handleTitleLevelChange">
          <div
            class="toolbar-item cursor-pointer w-[90px] h-[24px] flex items-center justify-center gap-1 outline-none"
          >
            <el-image src="/word/tool/title.svg" class="w-[16px] h-[16px]" />
            <span>{{ titleLevelLabel }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="item in titleLevelOptions"
                :key="item.value"
                :command="item.value"
              >
                <span :style="{ fontSize: item.size + 'px' }">{{
                  item.label
                }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-tooltip content="左对齐" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            :class="{ active: currentAlignment === RowFlex.LEFT }"
            @click="handleAlignmentChange(RowFlex.LEFT)"
          >
            <el-image src="/word/tool/left.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="居中对齐" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            :class="{ active: currentAlignment === RowFlex.CENTER }"
            @click="handleAlignmentChange(RowFlex.CENTER)"
          >
            <el-image src="/word/tool/center.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="右对齐" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            :class="{ active: currentAlignment === RowFlex.RIGHT }"
            @click="handleAlignmentChange(RowFlex.RIGHT)"
          >
            <el-image src="/word/tool/right.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="两端对齐" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            :class="{ active: currentAlignment === RowFlex.ALIGNMENT }"
            @click="handleAlignmentChange(RowFlex.ALIGNMENT)"
          >
            <el-image
              src="/word/tool/alignment.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>
        <el-tooltip content="分散对齐" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center"
            :class="{ active: currentAlignment === RowFlex.JUSTIFY }"
            @click="handleAlignmentChange(RowFlex.JUSTIFY)"
          >
            <el-image src="/word/tool/justify.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>

        <el-dropdown @command="handleRowMarginChange">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image
              src="/word/tool/row-margin.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="item in rowMarginOptions"
                :key="item.value"
                :command="item.value"
              >
                {{ item.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="handleListChange">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image src="/word/tool/list.svg" class="w-[16px] h-[16px]" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command=""> 取消列表 </el-dropdown-item>
              <el-dropdown-item command="decimal">
                <div>
                  <div>有序列表：</div>
                  <ul class="ml-4">
                    <li>1.________</li>
                  </ul>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="checkbox">
                <div>
                  <div>复选框列表：</div>
                  <ul style="list-style-type: '☑️ '" class="ml-8">
                    <li>________</li>
                  </ul>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="disc">
                <div>
                  <div>实心圆点列表：</div>
                  <ul style="list-style-type: disc" class="ml-8">
                    <li>________</li>
                  </ul>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="circle">
                <div>
                  <div>空心圆点列表：</div>
                  <ul style="list-style-type: circle" class="ml-8">
                    <li>________</li>
                  </ul>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="square">
                <div>
                  <div>空心方块列表：</div>
                  <ul style="list-style-type: square" class="ml-8">
                    <li>________</li>
                  </ul>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-divider direction="vertical" />
        <el-popover ref="tableInsertPanelRef" width="fit-content">
          <TableInsertPanel @insert="handleInsertTable" />
          <template #reference>
            <div
              class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            >
              <el-image src="/word/tool/table.svg" class="w-[16px] h-[16px]" />
            </div>
          </template>
        </el-popover>
        <el-tooltip content="插入图片" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleInsertImage"
          >
            <el-image src="/word/tool/image.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="超链接" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleHyperlink"
          >
            <el-image
              src="/word/tool/hyperlink.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>
        <el-dropdown @command="handleSeparator">
          <div
            :class="[
              'toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none',
              separatorActive ? 'active' : '',
            ]"
          >
            <el-image
              src="/word/tool/separator.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="0,0">
                <el-image src="/word/tool/line-single.svg" class="h-[16px]" />
              </el-dropdown-item>
              <el-dropdown-item command="1,1">
                <el-image src="/word/tool/line-dot.svg" class="h-[16px]" />
              </el-dropdown-item>
              <el-dropdown-item command="3,1">
                <el-image
                  src="/word/tool/line-dash-small-gap.svg"
                  class="h-[16px]"
                />
              </el-dropdown-item>
              <el-dropdown-item command="4,4">
                <el-image
                  src="/word/tool/line-dash-large-gap.svg"
                  class="h-[16px]"
                />
              </el-dropdown-item>
              <el-dropdown-item command="7,3,3,3">
                <el-image src="/word/tool/line-dash-dot.svg" class="h-[16px]" />
              </el-dropdown-item>
              <el-dropdown-item command="6,2,2,2,2,2">
                <el-image
                  src="/word/tool/line-dash-dot-dot.svg"
                  class="h-[16px]"
                />
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="handleWatermark">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image
              src="/word/tool/watermark.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="watermark">添加水印</el-dropdown-item>
              <el-dropdown-item command="remove-watermark"
                >删除水印</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-tooltip content="代码块" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleCodeBlock"
          >
            <el-image
              src="/word/tool/codeblock.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>
        <el-tooltip content="分页符" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handlePageBreak"
          >
            <el-image
              src="/word/tool/page-break.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>
        <el-dropdown @command="handleControl">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image src="/word/tool/control.svg" class="w-[16px] h-[16px]" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="text">文本</el-dropdown-item>
              <el-dropdown-item command="number">数值</el-dropdown-item>
              <el-dropdown-item command="enum">枚举</el-dropdown-item>
              <el-dropdown-item command="date">日期</el-dropdown-item>
              <el-dropdown-item command="checkbox">复选框</el-dropdown-item>
              <el-dropdown-item command="radio">单选框</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-tooltip content="复选框" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleCheckbox"
          >
            <el-image src="/word/tool/checkbox.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="单选框" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleRadio"
          >
            <el-image src="/word/tool/radio.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="Latex" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleLatex"
          >
            <el-image src="/word/tool/latex.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-dropdown @command="handleDate">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image src="/word/tool/date.svg" class="w-[16px] h-[16px]" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="date">
                {{ getCurrentDateString() }}
              </el-dropdown-item>
              <el-dropdown-item command="datetime">
                {{ getCurrentDateTimeString() }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-tooltip content="内容块" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleContentBlock"
          >
            <el-image src="/word/tool/block.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="签名" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleSignature"
          >
            <el-image
              src="/word/tool/signature.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
        </el-tooltip>
        <el-tooltip content="批注" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleComment"
          >
            <el-image src="/word/tool/comment.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-tooltip content="搜索与替换" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handleSearchReplace"
          >
            <el-image src="/word/tool/search.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-tooltip content="打印" placement="bottom">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            @click="handlePrint"
          >
            <el-image src="/word/tool/print.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>
        <el-dropdown @command="handleWord">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image src="/word/tool/word.svg" class="w-[16px] h-[16px]" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="import"> 导入 </el-dropdown-item>
              <el-dropdown-item command="export"> 导出 </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="word-main flex-1 flex justify-center w-full">
      <!-- 左侧目录面板 -->
      <div
        v-if="catalogVisible"
        ref="catalogPanelRef"
        class="catalog-panel fixed w-[280px] bg-white border border-gray-300 rounded-lg shadow-lg z-50 overflow-hidden"
        :style="{
          left: catalogPosition.x + 'px',
          top: catalogPosition.y + 'px',
          height: 'calc(100vh - 160px)',
          cursor: isDragging ? 'grabbing' : 'default',
        }"
        @mousedown="handleCatalogMouseDown"
        :class="{ dragging: isDragging }"
      >
        <div
          class="catalog-header flex items-center justify-between p-4 border-b border-gray-200 cursor-move select-none"
        >
          <span class="font-semibold text-gray-800">📑 文档目录</span>
          <el-button
            size="small"
            text
            @click="catalogVisible = false"
            class="text-gray-500 hover:text-gray-700"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="catalog-content p-2 h-full overflow-y-auto">
          <div
            v-if="catalogDatas.length === 0"
            class="text-center text-gray-500 mt-8"
          >
            暂无目录内容
          </div>
          <el-tree
            v-else
            :data="treeData"
            :props="treeProps"
            node-key="id"
            :expand-on-click-node="false"
            :default-expand-all="true"
            class="catalog-tree"
            @node-click="handleCatalogClick"
          >
            <template #default="{ node, data }">
              <span
                class="catalog-tree-node flex items-center w-full py-1"
                :class="`catalog-level-${data.level || 'default'}`"
              >
                <span
                  class="catalog-title text-sm text-gray-700 truncate flex-1"
                  :style="{
                    fontSize: getCatalogFontSize(data.level),
                    fontWeight: getCatalogFontWeight(data.level),
                  }"
                >
                  {{ data.name || "无标题" }}
                </span>
                <span class="text-xs text-gray-400 ml-2">
                  第{{ data.pageNo }}页
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧批注面板 -->
      <div
        v-if="commentVisible"
        ref="commentPanelRef"
        class="comment-panel fixed w-[320px] bg-white border border-gray-300 rounded-lg shadow-lg z-50 overflow-hidden"
        :style="{
          left: commentPosition.x + 'px',
          top: commentPosition.y + 'px',
          height: 'calc(100vh - 160px)',
          cursor: isDraggingComment ? 'grabbing' : 'default',
        }"
        @mousedown="handleCommentMouseDown"
        :class="{ dragging: isDraggingComment }"
      >
        <div
          class="comment-header flex items-center justify-between p-4 border-b border-gray-200 cursor-move select-none"
        >
          <span class="font-semibold text-gray-800">💬 批注列表</span>
          <el-button
            size="small"
            text
            @click="commentVisible = false"
            class="text-gray-500 hover:text-gray-700"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="comment-content p-2 h-full overflow-y-auto">
          <div
            v-if="commentList.length === 0"
            class="text-center text-gray-500 mt-8"
          >
            <div class="mb-4">
              <el-icon size="48" class="text-gray-300"
                ><ChatDotRound
              /></el-icon>
            </div>
            <p>暂无批注</p>
            <p class="text-xs mt-2">选择文本后点击批注按钮添加批注</p>
          </div>
          <div v-else class="comment-list space-y-3">
            <div
              v-for="(comment, index) in commentList"
              :key="comment.id"
              class="comment-item bg-gray-50 rounded-lg p-3 border border-gray-200 hover:bg-gray-100 transition-all duration-200 cursor-pointer"
              @click="handleCommentClick(comment)"
            >
              <!-- 批注头部 -->
              <div
                class="comment-item-header flex items-center justify-between mb-2"
              >
                <div class="flex items-center gap-2">
                  <div
                    class="comment-avatar w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center text-white text-xs font-bold"
                  >
                    {{ comment.userName.charAt(0).toUpperCase() }}
                  </div>
                  <span class="comment-user text-sm font-medium text-gray-700">
                    {{ comment.userName }}
                  </span>
                  <span class="comment-index text-xs text-gray-400"
                    >#{{ index + 1 }}</span
                  >
                </div>
                <el-button
                  size="small"
                  text
                  type="danger"
                  @click.stop="handleDeleteComment(comment.id)"
                  class="text-gray-400 hover:text-red-500"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>

              <!-- 引用文本 -->
              <div
                v-if="comment.rangeText"
                class="comment-quote mb-2 p-2 bg-blue-50 border-l-4 border-blue-300 rounded"
              >
                <span class="text-xs text-blue-600 font-medium"
                  >引用文本：</span
                >
                <span class="text-sm text-blue-800 block mt-1">{{
                  comment.rangeText
                }}</span>
              </div>

              <!-- 批注内容 -->
              <div
                class="comment-content-text text-sm text-gray-800 mb-2 leading-relaxed bg-white p-2 rounded border"
              >
                {{ comment.content }}
              </div>

              <!-- 时间戳 -->
              <div
                class="comment-time text-xs text-gray-500 flex items-center gap-1"
              >
                <el-icon size="12"><Clock /></el-icon>
                {{ comment.createdDate }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-scrollbar class="w-full">
        <div class="flex-1 w-full justify-center flex">
          <div class="word-editor" ref="wordEditorRef"></div>
        </div>
      </el-scrollbar>
    </div>
    <div class="word-footer flex items-center justify-between px-4">
      <div class="word-footer-left flex">
        <el-tooltip content="目录" placement="top">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            :class="{ active: catalogVisible }"
            @click="handleCatalog"
          >
            <el-image src="/word/tool/catalog.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>

        <el-tooltip content="批注面板" placement="top">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            :class="{ active: commentVisible }"
            @click="handleCommentPanel"
          >
            <el-image src="/word/tool/comment.svg" class="w-[16px] h-[16px]" />
          </div>
        </el-tooltip>

        <el-dropdown @command="handlePageMode">
          <div
            class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
          >
            <el-image
              src="/word/tool/page-mode.svg"
              class="w-[16px] h-[16px]"
            />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                command="paging"
                :class="{ 'active-menu-item': pageMode === 'paging' }"
              >
                分页
              </el-dropdown-item>
              <el-dropdown-item
                command="continuity"
                :class="{ 'active-menu-item': pageMode === 'continuity' }"
              >
                连页
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <div class="flex items-center gap-1">
          <span
            >页面：{{ documentStats.currentPage }}/{{
              documentStats.totalPages
            }}</span
          >
          <span>字数：{{ documentStats.wordCount }}</span>
          <span>行：{{ documentStats.lineCount }}</span>
          <span>列：{{ documentStats.columnCount }}</span>
        </div>
      </div>
      <div
        class="word-footer-center flex items-center space-x-4 text-xs text-gray-600"
      ></div>
      <div class="word-footer-right flex items-center">
        <!-- 页面缩放控件 -->
        <div
          class="flex items-center bg-gray-100 rounded-md border border-gray-300"
        >
          <el-tooltip content="缩小" placement="top">
            <button
              @click="handlePageScaleReduce"
              class="flex items-center justify-center w-6 h-6 text-gray-600 hover:text-gray-800 hover:bg-gray-200 transition-colors rounded-l-md"
              :disabled="pageScale <= 10"
            >
              <span class="text-sm font-bold">−</span>
            </button>
          </el-tooltip>

          <el-tooltip content="重置为100%" placement="top">
            <button
              @click="handlePageScaleReset"
              class="flex items-center justify-center min-w-[40px] h-6 px-2 text-xs text-gray-700 hover:bg-gray-200 transition-colors border-x"
            >
              {{ pageScale }}%
            </button>
          </el-tooltip>

          <el-tooltip content="放大" placement="top">
            <button
              @click="handlePageScaleAdd"
              class="flex items-center justify-center w-6 h-6 text-gray-600 hover:text-gray-800 hover:bg-gray-200 transition-colors rounded-r-md"
              :disabled="pageScale >= 200"
            >
              <span class="text-sm font-bold">+</span>
            </button>
          </el-tooltip>
        </div>

        <el-tooltip content="纸张大小" placement="bottom">
          <el-dropdown @command="handlePageSize">
            <div
              class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            >
              <el-image
                src="/word/tool/paper-size.svg"
                class="w-[16px] h-[16px]"
              />
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="794*1123"
                  :class="{ 'active-menu-item': pageSize === '794*1123' }"
                >
                  A4
                </el-dropdown-item>
                <el-dropdown-item
                  command="1593*2251"
                  :class="{ 'active-menu-item': pageSize === '1593*2251' }"
                >
                  A2
                </el-dropdown-item>
                <el-dropdown-item
                  command="1123*1593"
                  :class="{ 'active-menu-item': pageSize === '1123*1593' }"
                >
                  A3
                </el-dropdown-item>
                <el-dropdown-item
                  command="565*796"
                  :class="{ 'active-menu-item': pageSize === '565*796' }"
                >
                  A5
                </el-dropdown-item>
                <el-dropdown-item
                  command="412*488"
                  :class="{ 'active-menu-item': pageSize === '412*488' }"
                >
                  5号信封
                </el-dropdown-item>
                <el-dropdown-item
                  command="450*866"
                  :class="{ 'active-menu-item': pageSize === '450*866' }"
                >
                  6号信封
                </el-dropdown-item>
                <el-dropdown-item
                  command="609*862"
                  :class="{ 'active-menu-item': pageSize === '609*862' }"
                >
                  7号信封
                </el-dropdown-item>
                <el-dropdown-item
                  command="862*1221"
                  :class="{ 'active-menu-item': pageSize === '862*1221' }"
                >
                  9号信封
                </el-dropdown-item>
                <el-dropdown-item
                  command="813*1266"
                  :class="{ 'active-menu-item': pageSize === '813*1266' }"
                >
                  法律用纸
                </el-dropdown-item>
                <el-dropdown-item
                  command="813*1054"
                  :class="{ 'active-menu-item': pageSize === '813*1054' }"
                >
                  信纸
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-tooltip>
        <el-tooltip content="纸张方向" placement="bottom">
          <el-dropdown @command="handlePaperDirection">
            <div
              class="toolbar-item cursor-pointer w-[24px] h-[24px] flex items-center justify-center outline-none"
            >
              <el-image
                src="/word/tool/paper-direction.svg"
                class="w-[16px] h-[16px]"
              />
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="vertical"
                  :class="{ 'active-menu-item': paperDirection === 'vertical' }"
                >
                  纵向
                </el-dropdown-item>
                <el-dropdown-item
                  command="horizontal"
                  :class="{
                    'active-menu-item': paperDirection === 'horizontal',
                  }"
                >
                  横向
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-tooltip>
      </div>
    </div>
  </div>
  <HyperlinkDialog
    v-model="hyperlinkDialogVisible"
    @confirm="handleHyperlinkConfirm"
  />
  <CodeBlockDialog
    v-model="codeBlockDialogVisible"
    @confirm="handleCodeBlockConfirm"
  />
  <WatermarkDialog
    v-model="watermarkDialogVisible"
    @confirm="handleWatermarkConfirm"
    @cancel="handleWatermarkCancel"
  />
  <ControlDialog
    v-model="controlDialogVisible"
    :title="controlDialogTitle"
    :initial-data="controlDialogData"
    @confirm="handleControlConfirm"
    @cancel="handleControlCancel"
  />
  <LatexDialog v-model="latexDialogVisible" @confirm="handleLatexConfirm" />
  <ContentBlockDialog
    v-model="contentBlockDialogVisible"
    @confirm="handleContentBlockConfirm"
  />
  <SearchReplaceDialog
    v-model="searchReplaceDialogVisible"
    :index="searchIndex"
    :count="searchCount"
    @enter="handleEnter"
    @change="handleChange"
    @find-next="handleFindNext"
    @find-previous="handleFindPrevious"
    @replace="handleReplace"
    @replace-all="handleReplaceAll"
    @close="handleSearchReplaceClose"
  />
  <SignatureDialog
    v-model="signatureDialogVisible"
    @confirm="handleSignatureConfirm"
  />
  <CommentDialog
    v-model="commentDialogVisible"
    @confirm="handleCommentConfirm"
  />
</template>

<style scoped>
.word-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f2f4f7;
}

.word-header {
  height: 60px;
}

.word-main {
  flex: 1;
  overflow: hidden;
}

.word-editor {
}

.word-footer {
  height: 40px;
}

.toolbar-item {
}

.toolbar-item:hover {
  background-color: #eaecf0;
}

.toolbar-item.active {
  background-color: #eaecf0;
}

/* SVG变灰色 - 使用CSS滤镜 */
.toolbar-item.disabled :deep(.el-image img) {
  filter: grayscale(100%);
  opacity: 0.6;
}

/* 字体选择器样式 */
.font-selector :deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.font-selector :deep(.el-select .el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.font-selector :deep(.el-select .el-input__wrapper.is-focus) {
  border-color: #409eff;
}

/* 目录面板样式 */
.catalog-panel {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(8px);
  background-color: rgba(255, 255, 255, 0.95);
  transition: box-shadow 0.3s ease;
}

.catalog-panel:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.catalog-header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  user-select: none;
}

.catalog-header:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.catalog-header:active {
  background: linear-gradient(135deg, #dee2e6 0%, #ced4da 100%);
}

.catalog-content {
  max-height: calc(100% - 60px); /* 减去头部高度 */
}

/* el-tree 目录样式 */
.catalog-tree {
  background: transparent;
}

.catalog-tree :deep(.el-tree-node) {
  margin-bottom: 2px;
}

.catalog-tree :deep(.el-tree-node__content) {
  height: auto;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}

.catalog-tree :deep(.el-tree-node__content:hover) {
  background-color: #f0f2f5;
  border-left-color: #409eff;
  transform: translateX(2px);
}

.catalog-tree :deep(.el-tree-node__expand-icon) {
  color: #409eff;
  font-size: 14px;
}

.catalog-tree :deep(.el-tree-node__expand-icon.is-leaf) {
  color: transparent;
}

.catalog-tree-node {
  user-select: none;
  width: 100%;
}

.catalog-title {
  line-height: 1.4;
}

/* 拖拽时的样式 */
.catalog-panel.dragging {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
  transform: rotate(1deg);
}

/* 不同级别标题的样式 */
.catalog-level-first .catalog-title {
  font-weight: 600;
  color: #1f2937;
}

.catalog-level-second .catalog-title {
  font-weight: 500;
  color: #374151;
}

.catalog-level-third .catalog-title {
  font-weight: 500;
  color: #6b7280;
}

.catalog-level-fourth .catalog-title,
.catalog-level-fifth .catalog-title,
.catalog-level-sixth .catalog-title {
  font-weight: 400;
  color: #9ca3af;
}

/* 页面模式 active 样式 */
:deep(.active-menu-item) {
  background-color: #e6f7ff !important;
  color: #409eff !important;
  font-weight: 500;
}

:deep(.active-menu-item:hover) {
  background-color: #bae7ff !important;
}

/* 底部状态栏样式 */
.word-footer-center {
  user-select: none;
}

.word-footer-center span {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.02);
  border: 1px solid rgba(0, 0, 0, 0.06);
  transition: all 0.2s ease;
}

.word-footer-center span:hover {
  background-color: rgba(0, 0, 0, 0.05);
  border-color: rgba(0, 0, 0, 0.1);
}

/* 页面缩放控件样式 */
.word-footer-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.word-footer-right button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.word-footer-right button:disabled:hover {
  background-color: inherit !important;
  color: inherit !important;
}

/* 批注面板样式 */
.comment-panel {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(8px);
  background-color: rgba(255, 255, 255, 0.95);
  transition: box-shadow 0.3s ease;
}

.comment-panel:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.comment-header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  user-select: none;
}

.comment-header:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.comment-header:active {
  background: linear-gradient(135deg, #dee2e6 0%, #ced4da 100%);
}

.comment-content {
  max-height: calc(100% - 60px); /* 减去头部高度 */
}

.comment-item {
  transition: all 0.2s ease;
  user-select: none;
  position: relative;
}

.comment-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.comment-item:active {
  transform: translateY(0);
}

.comment-quote {
  background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
  border-left: 4px solid #3b82f6;
}

.comment-avatar {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}

.comment-content-text {
  background: #fafafa;
  border: 1px solid #e5e7eb;
  line-height: 1.5;
}

.comment-index {
  background: rgba(156, 163, 175, 0.1);
  padding: 1px 6px;
  border-radius: 10px;
  font-weight: 500;
}

/* 拖拽时的样式 */
.comment-panel.dragging {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
  transform: rotate(1deg);
}

/* 空状态样式 */
.comment-content .text-gray-500 {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
